<?php

namespace Biz\service\esSearch;

use Biz\model\store\MStoreContent as mMStoreContent;
use Doraemon\cache\ArticleCounter;
use Doraemon\cache\BlankCounter;
use Doraemon\cache\PhotoCounter;
use Doraemon\cache\UserCounter;
use Doraemon\service\AdmUserTag;
use Doraemon\service\Article;
use Doraemon\service\Blank;
use Doraemon\service\es\EsStoreContent;
use Doraemon\service\esSearch\Common;
use Doraemon\service\Photo\Schedule;
use Doraemon\service\Photos;
use Doraemon\service\User;
use Doraemon\tools\BlockType;
use Doraemon\tools\Filter;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log;

class StoreContent
{

    public static function syncSave($data)
    {
        if (isset($data["data"]["id"])) {
            if (isset($data["type"]) && in_array($data["type"], [Common::TYPE_ADD, Common::TYPE_UPDATE])) {
                self::_handle($data["data"]["id"]);
            }
        }
    }

    private static function _handle($priKey)
    {
        try {
            self::_updateInfo($priKey);
        } catch (\Exception $e) {
            Log::error('StoreContent-ES更新执行失败', ['id' => $priKey, 'error' => $e->getMessage()]);
        }
    }

    private static function _updateInfo($id)
    {
        $id = intval($id);

        if (!$id) {
            throw new \Exception('请输入id');
        }

        $info = mMStoreContent::getInfo($id);

        if (!(is_array($info) && $info)) {
            throw new \Exception('门店内容不存在id :' . $id);
        }

        $objId = $info["obj_id"];

        $uid = IdParse::getUid($objId);

        $userInfo = User::getBasicUserInfo($uid);

        $user_type = $userInfo['type'];

        $type = IdParse::getType($objId);

        $data = array();

        $counter = [];

        switch ($type) {
            case BlockType::TYPE_BLANK:
                $data = Blank::getBlank($objId);
                $counter = BlankCounter::getOne($objId);
                break;
            case BlockType::TYPE_ARTICLE:
                $data = Article::getArticle($objId);
                $counter = ArticleCounter::getOne($objId);
                break;
            case BlockType::TYPE_PHOTO:
            case BlockType::TYPE_ANSWER:
                $data = Photos::getPhoto($objId);
                $counter = PhotoCounter::getOne($objId);
                $remark = str_replace('#', ' ', Utils::emojiStrConvert($data['remark']));
                // 如果有点图标签，那么则加入
                $imgTag = "";
                $imgTagJson = Schedule::getNoteImgTag($objId);
                if (Utils::extractBrandWithProductStr($imgTagJson)) {
                    $imgTagStr = Utils::extractBrandWithProductStr($imgTagJson);
                    $remark .= ' itg: ' . $imgTagStr;
                    // 点图标签
                    if (trim($imgTagStr)) {
                        $imgTag = trim($imgTagStr);
                    }
                }
                if (!(isset($data["title"]) && $data["title"])) {
                    $data['title'] = $remark;
                }
                $data['img_tag'] = $imgTag;
                $data['publish_time'] = $data["addtime"];
                break;
            default :
                throw new \Exception('没有对应处理对象');
        }

        $master_tags = AdmUserTag::getByUid($uid);

        $content_str = '';
        if ($type == BlockType::TYPE_BLANK) {
            $content_arr = json_decode($data['content_block'], 'true') ?: [];
            if ($content_arr) {
                $content_type_arr = array_filter($content_arr, function ($val) {
                    return ($val['type'] == 1 || $val['type'] == 2) ? true : false;
                }) ?: [];
                if ($content_type_arr && is_array($content_arr)) {
                    $content = array_column($content_type_arr, 'content');
                }
                if ($content && is_array($content)) {
                    $content = array_column($content, 'text');
                    $content_str = implode('', $content);
                }
            }
        } else {
            if ($type == BlockType::TYPE_PHOTO || $type == BlockType::TYPE_ANSWER) {
                $content_str = $remark;
            } else {
                $content_str = Filter::filterContent($data['content']);
            }
        }

        $createdAt = $info["created_at"] !== "0000-00-00 00:00:00" ? $info["created_at"] : 0;

        $updateAt = $info["updated_at"] !== "0000-00-00 00:00:00" ? $info["updated_at"] : 0;

        if ($createdAt) {
            $createdAt = strtotime($createdAt);
        }

        if ($updateAt) {
            $updateAt = strtotime($updateAt);
        }

        $inputData = [
            'store_id' => (int)$info["store_id"],
            'owner_uid' => (int)$uid,
            'owner_user_type' => (int)$user_type,
            'obj_type' => (int)$type,
            'obj_id' => (string)$objId,
            'content_status' => (int)$info["content_status"],
            'content_module' => (int)$info["content_module"],
            'created_at' => (int)$createdAt,
            'updated_at' => (int)$updateAt,
            'top_time' => (int)$info["top_time"],
            'addtime' => (int)$data['publish_time'],
            'admin_tag' => str_replace(',', ' ', $data['admin_tag']),
            'title' => $data['title'],
            'content' => $content_str,
            'master_tag' => (string)implode(' ', $master_tags),
            'admin_score' => $data['admin_score'],
            'status' => $data['status'],
            'like' => $counter['like'],
            'share' => $counter['share'],
            'favorite' => $counter['favorite'],
            'comment' => $counter['comment'],
            'read' => $counter['read'],
            'show_type' => isset($data['show_type']) ? intval($data['show_type']) : 0,
            'topic_activity_id' => isset($data['topic_activity_id']) && intval($data['topic_activity_id']) ? intval($data['topic_activity_id']) : 0,
            'content_type' => (int)$info["content_type"],
            'create_from' => (int)$info["create_from"],
        ];

        // 点图标签
        $inputData["img_tag"] = "";
        if (isset($data['img_tag'])) {
            $inputData["img_tag"] = $data['img_tag'];
        }

        // 用户粉丝数
        $userCount = UserCounter::getOne($uid);
        $inputData["fans"] = 0;
        if (isset($userCount["fans"]) && $userCount["fans"]) {
            $inputData["fans"] = $userCount["fans"];
        }

        $rs = EsStoreContent::post($id, $inputData);

        if ($rs && isset($rs['code']) && $rs['code'] == 1) {
            return true;
        }

        throw new \Exception('处理失败');

    }

}